package com.weimob.mcloud.wechatwork.customer.mq.handler.employee;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.weimob.mcloud.wechatwork.core.adapter.enums.cdp.CDPMarkTypeEnum;
import com.weimob.mcloud.wechatwork.core.adapter.enums.cdp.CdpMarkMessageEventEnum;
import com.weimob.mcloud.wechatwork.core.adapter.pojo.dto.cdp.request.customer.CDPUserMarkDTO;
import com.weimob.mcloud.wechatwork.core.adapter.service.cdp.CdpUserAdapterService;
import com.weimob.mcloud.wechatwork.core.base.MultiResponse;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.CustomerEmployeeRelation;
import com.weimob.mcloud.wechatwork.core.entity.relation.customer.Customer;
import com.weimob.mcloud.wechatwork.core.entity.relation.employee.Employee;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.customer.ExternalUserTypeEnum;
import com.weimob.mcloud.wechatwork.core.enums.employee.EmployeeActiveStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.employee.EmployeeStatusEnum;
import com.weimob.mcloud.wechatwork.core.service.customer.CustomerService;
import com.weimob.mcloud.wechatwork.core.service.customer.request.CusEmpIdRequest;
import com.weimob.mcloud.wechatwork.core.service.customer.request.CusEmpUpdateByEmpIdsRequest;
import com.weimob.mcloud.wechatwork.core.service.customer.request.CustomerByIdsRequest;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisBaseInfo;
import com.weimob.mcloud.wechatwork.customer.domain.ArtemisConstant;
import com.weimob.mcloud.wechatwork.customer.domain.CdpDataJsonInfo;
import com.weimob.mcloud.wechatwork.customer.domain.EmployeeAuthorizeChangeInfo;
import com.weimob.mcloud.wechatwork.customer.domain.artemis.CustomerChangeEventMsg;
import com.weimob.mcloud.wechatwork.customer.domain.artemis.CustomerSearchInitEventMsg;
import com.weimob.mcloud.wechatwork.customer.externalDependencyProxy.usermanagement.EmployeeProxy;
import com.weimob.mcloud.wechatwork.customer.service.impl.ArtemisService;
import com.weimob.mcloud.wechatwork.customer.service.user.enums.CDPFlowStatusEnum;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerServiceProxy;
import com.weimob.mcloud.wechatwork.customer.third.customer.CustomerThird;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.weimob.mcloud.wechatwork.customer.service.user.constant.RedisKeyConstant.CUSTOMER_SEARCH_SEAT_INTERVAL_LOCK;

/**
 * @Author yu liu  2022/5/24 23:59
 * Description
 * Version 1.0.0
 **/
@Service
@Slf4j
public class EmployeeAuthorizeChangeHandler {

    @Reference
    private PrivateSphereService privateSphereService;

    @Autowired
    private CustomerServiceProxy customerServiceProxy;

    @Reference
    CustomerService customerService;

    @Value("${customer.ids.handler.partitioncount:10}")
    private Integer partitionCount;

    @Autowired
    private CustomerThird customerThird;

    @Resource
    private ArtemisService artemisService;

    @Reference
    CdpUserAdapterService cdpUserAdapterService;

    @Value("${employee.ids.handler.partitioncount:50}")
    private Integer employeeIdPartition;

    @Value("${every.employee.max.customer.size:1000}")
    private Integer maxCustomerIdsSize;

    @Autowired
    @Qualifier("employeeAuthChangeSyncThreadPool")
    private ThreadPoolTaskExecutor employeeAuthChangeSyncThreadPool;

    @Value("${customer.employee.relation.switch.write.old:true}")
    private boolean writeOldTableFlag;


    @Value("${customer.employee.relation.switch.write.new:true}")
    private boolean writeNewTableFlag;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private EmployeeProxy employeeProxy;

    /**
     * 员工状态hanlder
     *
     * @param employeeAuthorizeChangeInfo
     * @return
     */
    public Boolean handleEmployeeAuthorizeChange(EmployeeAuthorizeChangeInfo employeeAuthorizeChangeInfo) {
        //获取私域
        String corpId = employeeAuthorizeChangeInfo.getCorpId();
        Long bosId = employeeAuthorizeChangeInfo.getBosId();
        PrivateSphere privateSphere = new PrivateSphere();
        privateSphere.setCorpId(corpId);
        privateSphere.setBosId(bosId);
        SoaResponse<PrivateSphere, Void> fetchPrivateSphere = privateSphereService.simpleFetch(privateSphere);
        if (!SoaUtil.isSucc(fetchPrivateSphere) || Objects.isNull(fetchPrivateSphere.getResponseVo())) {
            log.info("处理员工授权范围变更/坐席变更，查询私域信息失败,corpId:{}", corpId);
            return Boolean.FALSE;
        }
        privateSphere = fetchPrivateSphere.getResponseVo();
        //根据员工id+事件类型，换取符合条件的员工数据
        List<Employee> employeeList = batchFetchEmployee(privateSphere, employeeAuthorizeChangeInfo);
        if (CollectionUtils.isEmpty(employeeList)) {
            log.error("soaResponse#employeeList is empty {}:", employeeAuthorizeChangeInfo.getEmployeeIds());
            return Boolean.FALSE;
        }

        //拿到员工ids，根据状态合并后做分类
        List<String> unAuthEmpIds = new ArrayList<>();
        List<String> authEmpIds = new ArrayList<>();
        for (Employee employee : employeeList) {
            if (Objects.isNull(employee)) {
                continue;
            }
            //获取员工的状态->合并出客户状态
            EmployeeStatusEnum status = employee.getStatus();
            EmployeeActiveStatusEnum activeStatus = employee.getActiveStatus();
            String id = employee.getId();
            if (EmployeeStatusEnum.USER_UN_AUTHORIZATION == status
                    || EmployeeActiveStatusEnum.INACTIVE == activeStatus) {
                unAuthEmpIds.add(id);
            } else {
                authEmpIds.add(id);
            }
        }

        //根据员工终态状态分类处理
        if (CollectionUtils.isNotEmpty(authEmpIds)) {
            //授权-则需要查询未授权的客户再去修改
            handleAuthorizeByCustomerStatus(authEmpIds, privateSphere, CustomerStatusEnum.UNAUTHORIZED);
        }

        if (CollectionUtils.isNotEmpty(unAuthEmpIds)) {
            //未授权-则需要查询已授权的客户再去修改
            handleAuthorizeByCustomerStatus(unAuthEmpIds, privateSphere, CustomerStatusEnum.DEFAULT);
        }
        return true;
    }


    /**
     * 跟进状态滚动
     **/
    public void handleAuthorizeByCustomerStatus(List<String> employeeIdList, PrivateSphere privateSphere, CustomerStatusEnum customerStatusEnum) {
        try {
            long startTime = System.currentTimeMillis();
            String corpId = privateSphere.getCorpId();
            //滚动查询，获取所有的当前员工ids对应的客户员工关系数据
            List<CustomerEmployeeRelation> relationList = customerServiceProxy.scrollRelationByEmpIds(employeeIdList, corpId, customerStatusEnum);
            if (CollectionUtils.isEmpty(relationList)) {
                log.warn("removeAuthorizeCustomerHandler query relationList is empty,employeeIdList:{}", JSON.toJSON(employeeIdList));
                return;
            }
            //1.1 更新客户关系表状态 正常变为未授权
            //获取员工和客户ids
            Set<String> updateEmployeeIds = new HashSet<>();
            Set<String> updateCustomerIds = new HashSet<>();
            List<CusEmpIdRequest> updateRelationList = new ArrayList<>();
            for (CustomerEmployeeRelation employeeRelation : relationList) {
                updateCustomerIds.add(employeeRelation.getCustomerId());
                Employee employee = employeeRelation.getEmployee();
                if (Objects.nonNull(employee) && Objects.nonNull(employee.getId())) {
                    updateEmployeeIds.add(employee.getId());
                    //存客户员工关系
                    CusEmpIdRequest cusEmpIdRequest = new CusEmpIdRequest();
                    cusEmpIdRequest.setCustomerId(employeeRelation.getCustomerId());
                    cusEmpIdRequest.setEmployeeId(employee.getId());
                    updateRelationList.add(cusEmpIdRequest);
                }
            }

            if (CollectionUtils.isEmpty(updateCustomerIds) || CollectionUtils.isEmpty(updateEmployeeIds)) {
                log.warn("员工坐席/授权范围变更查询的客户id员工ids为空");
                return;
            }
            log.info("处理员工授权范围/坐席变更消息开始，消息体：{},customerStatus:{}", JSON.toJSON(employeeIdList), customerStatusEnum.getCode());
            if (updateCustomerIds.size() > maxCustomerIdsSize) {
                log.info("处理员工授权范围/坐席变更消息开始,使用线程池处理,受影响客户数:{},客户ids数量大于{}", updateCustomerIds.size(), maxCustomerIdsSize);
                employeeAuthChangeSyncThreadPool.execute(() -> bizHandlerByStatus(customerStatusEnum, privateSphere, updateEmployeeIds, updateCustomerIds, updateRelationList));
            } else {
                bizHandlerByStatus(customerStatusEnum, privateSphere, updateEmployeeIds, updateCustomerIds, updateRelationList);
            }
            log.info("处理员工授权范围/坐席变更消息结束,employeeId:{},耗时: {}", JSON.toJSON(employeeIdList), System.currentTimeMillis() - startTime);
        } catch (Exception e) {
            log.error("处理员工移除授权范围/坐席变更消息失败:", e);
        }
    }

    /**
     * 根据客户ids 拆分为异步和同步处理
     *
     * @param customerStatusEnum 客户状态
     * @param privateSphere      私域
     * @param updateEmployeeIds  员工ids
     * @param updateCustomerIds  客户ids
     */
    private void bizHandlerByStatus(CustomerStatusEnum customerStatusEnum, PrivateSphere privateSphere, Set<String> updateEmployeeIds, Set<String> updateCustomerIds, List<CusEmpIdRequest> updateRelationList) {
        if (CustomerStatusEnum.DEFAULT.equals(customerStatusEnum)) {
            this.removeAuthorizeCustomerHandler(privateSphere, updateEmployeeIds, updateCustomerIds, updateRelationList);
        }
        if (CustomerStatusEnum.UNAUTHORIZED.equals(customerStatusEnum)) {
            this.addAuthorizeCustomerHandler(privateSphere, updateEmployeeIds, updateCustomerIds, updateRelationList);
        }
    }

    /**
     * 员工移除授权范围/坐席变更处理
     *
     * @param privateSphere
     * @param updateEmployeeIds
     * @param updateCustomerIds
     */
    private void removeAuthorizeCustomerHandler(PrivateSphere privateSphere, Set<String> updateEmployeeIds, Set<String> updateCustomerIds, List<CusEmpIdRequest> updateRelationList) {
        // 1.更新客户员工关系状态
        String corpId = privateSphere.getCorpId();
        if (CollectionUtils.isEmpty(updateCustomerIds) || CollectionUtils.isEmpty(updateEmployeeIds)) {
            log.warn("员工坐席/授权范围变更查询的客户id员工ids为空");
            return;
        }

        //更新客户员工关系表的标识-移除授权范围则改为未授权
        updateRelationByEmployee(privateSphere, updateEmployeeIds, CustomerStatusEnum.UNAUTHORIZED, updateRelationList);

        //2.更新主表，判断这一批客户，那些是需要更新customer主表的，status-> all for one
        List<String> updateMainTableList = new ArrayList<>();
        List<String> otherCustomerIds = new ArrayList<>();
        for (String customerId : updateCustomerIds) {
            //判断关联的员工的状态是不是全部为未授权
            Long count = customerServiceProxy.fetchCustomerEmployeeRelationCount(corpId, customerId, null, CustomerStatusEnum.DEFAULT);
            //当前客户所有的关系数据都未授权，则代表此客户主表的status将需要更新
            if (count != null && count == 0L) {
                updateMainTableList.add(customerId);
            } else {
                otherCustomerIds.add(customerId);
            }
        }

        List<Customer> customerList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(updateMainTableList)) {
            //补全customer的详细数据，主要为了后续externalUserId换取wid
            //这一步是为了换取externalUserId+外部联系人类型
            List<Customer> updateCustomers = fetchCustomerIds(updateMainTableList, privateSphere);
            //换出externalUserIds
            List<String> customerIds = updateCustomers.stream().map(Customer::getId).collect(Collectors.toList());
            //2.1 更新主表为未授权
            Boolean result = updateCustomerStatusBatch(customerIds, corpId, CustomerStatusEnum.UNAUTHORIZED);
            if (Boolean.FALSE.equals(result)) {
                log.error("移除授权/坐席-更新客户主表失败,customerIds:{},corpId:{}", customerIds, corpId);
                return;
            }
            //赋值为未授权
            for (Customer customer : updateCustomers) {
                customer.setStatus(CustomerStatusEnum.UNAUTHORIZED);
                customerList.add(customer);
            }

        }

        //补全otherCustomerIds对应的customer数据
        if (CollectionUtils.isNotEmpty(otherCustomerIds)) {
            List<Customer> customers = fetchCustomerIds(new ArrayList<>(otherCustomerIds), privateSphere);
            customerList.addAll(customers);
        }

        //3.通知客搜es检索
        for (Customer customer : customerList) {
            Long superWid = customerThird.getSuperWid(privateSphere.getBosId(), customer.getExternalUserid(), corpId);
            if (Objects.isNull(superWid)) {
                log.error("员工坐席/授权范围变更,未获取到当前客户的wid,externalUserId:{},corpId:{}", customer.getExternalUserid(), corpId);
                continue;
            }
            //3.1 通知客搜
            if (ExternalUserTypeEnum.WECHAT_CUSTOMER.getCode().equals(customer.getExternalUserType().getCode())) {
                updateCustomerSearchMsg(superWid, privateSphere);
            }
            //3.2.cdp客户属性打点
            //是否好友
            int friended = isFriended(customer.getId(), corpId);
            markCDPMsg(privateSphere, superWid, customer, friended);
        }
    }

    /**
     * 添加坐席或者授权范围
     *
     * @param privateSphere
     * @param updateEmployeeIds
     * @param updateCustomerIds
     */
    private void addAuthorizeCustomerHandler(PrivateSphere privateSphere, Set<String> updateEmployeeIds, Set<String> updateCustomerIds, List<CusEmpIdRequest> updateRelationList) {
        //添加坐席或者授权范围
        String corpId = privateSphere.getCorpId();
        if (CollectionUtils.isEmpty(updateEmployeeIds) || CollectionUtils.isEmpty(updateCustomerIds)) {
            log.error("addAuthorizeCustomerHandler employeeIds or updateCustomerIds is empty");
            return;
        }

        //2.更新员工客户关系数据-无效变有效
        updateRelationByEmployee(privateSphere, updateEmployeeIds, CustomerStatusEnum.DEFAULT, updateRelationList);

        //换取到员工关联全部的customer详细数据
        //这一步是为了换取externalUserId+外部联系人类型
        List<Customer> customerList = fetchCustomerIds(new ArrayList<>(updateCustomerIds), privateSphere);
        if (CollectionUtils.isEmpty(customerList)) {
            return;
        }
        //换出customerIds
        List<String> customerIds = customerList.stream().map(Customer::getId).collect(Collectors.toList());
        //2.2更新主表为授权
        Boolean result = updateCustomerStatusBatch(customerIds, corpId, CustomerStatusEnum.DEFAULT);
        if (Boolean.FALSE.equals(result)) {
            log.error("新增授权/坐席-更新客户主表失败,customerIds:{},corpId:{}", customerIds, corpId);
            return;
        }

        //3.通知es检索
        for (Customer customer : customerList) {
            Long superWid = customerThird.getSuperWid(privateSphere.getBosId(), customer.getExternalUserid(), corpId);
            if (Objects.isNull(superWid)) {
                continue;
            }
            //通知客搜-添加授权/坐席，客户状态变为有效
            if (ExternalUserTypeEnum.WECHAT_CUSTOMER.getCode().equals(customer.getExternalUserType().getCode())) {
                updateCustomerSearchMsg(superWid, privateSphere);
            }

            customer.setStatus(CustomerStatusEnum.DEFAULT);
            //推送cdp流失状态+好友标识
            int friended = isFriended(customer.getId(), corpId);
            markCDPMsg(privateSphere, superWid, customer, friended);
        }
    }


    /**
     * 判断是否是好友
     *
     * @param customerId
     * @param corpId
     * @return
     */
    private int isFriended(String customerId, String corpId) {
        Long count = customerServiceProxy.fetchCustomerEmployeeRelationCount(corpId, customerId, true, CustomerStatusEnum.DEFAULT);
        if (count > 0) {
            return CDPFlowStatusEnum.NOT_FLOW_STATUS.getCode();
        } else {
            return CDPFlowStatusEnum.LOST_STATUS.getCode();
        }
    }


    /**
     * 发送授权状态变更的消息-通知客搜
     *
     * @param privateSphere privateSphere
     */
    public void updateCustomerSearchMsg(Long wid, PrivateSphere privateSphere) {
        String key = String.format(CUSTOMER_SEARCH_SEAT_INTERVAL_LOCK, privateSphere.getBosId(), privateSphere.getProductInstanceId(), wid);
        Boolean result = redisTemplate.opsForValue().setIfAbsent(key, "", 1, TimeUnit.SECONDS);
        if (Boolean.FALSE.equals(result)) {
            log.warn("授权状态/坐席变更-通知客搜客户变更, bosId:{}, wid:{}, 3s内已经发送过", privateSphere.getBosId(), wid);
            return;
        }
        CustomerChangeEventMsg customerChangeEventMsg = new CustomerChangeEventMsg();
        customerChangeEventMsg.setBosId(privateSphere.getBosId());
        customerChangeEventMsg.setSourceProductInstanceId(privateSphere.getProductInstanceId());
        customerChangeEventMsg.setSourceProductId(privateSphere.getProductId());
        customerChangeEventMsg.setWids(Lists.newArrayList(wid));
        ArtemisBaseInfo artemisBaseInfo = new ArtemisBaseInfo();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.CORE_EXTERNALUSER_CHANG_EVENT);
        artemisBaseInfo.setEvent(customerChangeEventMsg);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        log.info("授权状态/坐席变更-通知客搜客户变更, bosId:{}, wid:{}", privateSphere.getBosId(), wid);
        artemisService.sendToArtemis(artemisBaseInfo,privateSphere.getBosId());
    }

    /**
     * 发送授权状态变更的消息-通知客搜
     *
     * @param wid
     * @param privateSphere
     * @param authorizationState
     */
    private void sendAuthStatusChangeMsg(Long wid, PrivateSphere privateSphere, Integer authorizationState) {
        if (Objects.isNull(wid)) {
            return;
        }
        CustomerSearchInitEventMsg customerSearchMsg = new CustomerSearchInitEventMsg();
        customerSearchMsg.setBosId(privateSphere.getBosId());
        customerSearchMsg.setSourceProductInstanceId(privateSphere.getProductInstanceId());
        customerSearchMsg.setSourceProductId(privateSphere.getProductId());
        customerSearchMsg.setAuthorizationState(authorizationState);
        customerSearchMsg.setWid(wid);
        ArtemisBaseInfo<CustomerSearchInitEventMsg> artemisBaseInfo = new ArtemisBaseInfo<>();
        artemisBaseInfo.setTopic(ArtemisConstant.Topic.CORE_EXTERNALUSER_INIT_EVENT);
        artemisBaseInfo.setEvent(customerSearchMsg);
        artemisBaseInfo.setProducer(ArtemisConstant.USER);
        log.info("员工授权/坐席事件，客户状态变更，推送到搜索服务消息, request:{}", JSON.toJSONString(artemisBaseInfo));
        artemisService.sendToArtemis(artemisBaseInfo, privateSphere.getBosId());
    }


    /**
     * 获取客户详情数据
     *
     * @param customerIds
     */
    private List<Customer> fetchCustomerIds(List<String> customerIds, PrivateSphere privateSphere) {
        List<Customer> customerList = new ArrayList<>();
        //分批查询
        List<List<String>> customerIdPartition = Lists.partition(new ArrayList<>(customerIds), partitionCount);
        for (List<String> customerIdListItem : customerIdPartition) {
            try {
                List<Customer> customerResList = customerServiceProxy.fetchCustomerByIds(customerIdListItem, null, privateSphere);
                if (CollectionUtils.isEmpty(customerResList)) {
                    continue;
                }
                customerList.addAll(customerResList);
            } catch (Exception e) {
                log.error("查询客户信息失败,error", e);
            }
        }
        return customerList;
    }


    private Boolean updateCustomerStatusBatch(List<String> customerIds, String corpId, CustomerStatusEnum customerStatusEnum) {
        if (CollectionUtils.isEmpty(customerIds)) {
            return false;
        }
        HashSet<String> set = new HashSet<>(customerIds);
        List<List<String>> list = Customer.partitionExternalIds(set, partitionCount);
        log.info("员工授权/坐席事件，分批更新客户状态, corpId:{},customerIds.size:{}, batch.size:{}", corpId, customerIds.size(), list.size());
        for (List<String> ids : list) {
            CustomerByIdsRequest customerUpdateReq = new CustomerByIdsRequest();
            customerUpdateReq.setCustomerIds(ids);
            Customer updateCustomer = new Customer();
            updateCustomer.setCorpId(corpId);
            updateCustomer.setStatus(customerStatusEnum);
            customerUpdateReq.setCustomer(updateCustomer);
            SoaResponse<Integer, ?> soaResponse = customerService.updateCustomerStatusBatch(customerUpdateReq);
            if (!SoaUtil.isSucc(soaResponse)) {
                log.error("员工授权/坐席事件，批量更新客户状态失败, corpId:{},externalUserIds:{}", corpId, JSON.toJSON(ids));
                return false;
            }
        }
        return true;
    }

    /**
     * 分批查询员工数据
     *
     * @param privateSphere
     * @param changeInfo
     * @return
     */
    private List<Employee> batchFetchEmployee(PrivateSphere privateSphere, EmployeeAuthorizeChangeInfo changeInfo) {
        //获取ids
        List<String> employeeIds = changeInfo.getEmployeeIds();

        List<List<String>> partitionList = Lists.partition(employeeIds, employeeIdPartition);
        List<Employee> employeeResDTOList = new ArrayList<>();
        for (List<String> ids : partitionList) {

            MultiResponse<Employee> multiResponse = employeeProxy.getByEmployeeIdOrTxUserIds(privateSphere, ids, null);
            if (Objects.isNull(multiResponse) || CollectionUtils.isEmpty(multiResponse.getDataList())) {
                log.error("soaResponse#batchFetchEmployee,ids: {}:", JSON.toJSON(ids));
                continue;
            }
            List<Employee> employees = multiResponse.getDataList();
            employeeResDTOList.addAll(employees);
        }

        return employeeResDTOList;
    }

    /**
     * 更新关系表数据
     *
     * @param privateSphere
     * @param employeeIds
     */
    private void updateRelationByEmployee(PrivateSphere privateSphere, Set<String> employeeIds, CustomerStatusEnum customerStatusEnum, List<CusEmpIdRequest> updateRelationList) {
        if (CollectionUtils.isEmpty(employeeIds)) {
            log.error("employeeIds is empty");
            return;
        }
        if (writeOldTableFlag) {
            //如果开了双写还是走原来的逻辑
            String corpId = privateSphere.getCorpId();
            employeeIds.forEach(employeeId -> {
                CustomerEmployeeRelation updateEmployeeRelation = new CustomerEmployeeRelation();
                updateEmployeeRelation.setCorpId(corpId);
                Employee employee = new Employee();
                employee.setId(employeeId);
                updateEmployeeRelation.setEmployee(employee);
                updateEmployeeRelation.setStatus(customerStatusEnum);
                customerService.updateCustomerEmployeeRelation(updateEmployeeRelation);
            });
        }
        //走新的逻辑-更新客户员工关系表
        if (writeNewTableFlag) {
            try {
                CusEmpUpdateByEmpIdsRequest cusEmpUpdateByEmpIdsRequest = new CusEmpUpdateByEmpIdsRequest();
                cusEmpUpdateByEmpIdsRequest.setCorpId(privateSphere.getCorpId());
                cusEmpUpdateByEmpIdsRequest.setRelationList(updateRelationList);
                cusEmpUpdateByEmpIdsRequest.setStatus(customerStatusEnum.getCode());
                customerService.updateCustomerEmployeeRelationByEmpIds(cusEmpUpdateByEmpIdsRequest);
            } catch (Exception e) {
                log.error("updateCustomerEmployeeRelationByEmpIds error", e);
            }
        }

    }


    /**
     * cdp 属性打点
     *
     * @param privateSphere
     * @param wid
     * @param customer
     */
    private void markCDPMsg(PrivateSphere privateSphere, Long wid, Customer customer, Integer friended) {
        // 4.cdp客户属性打点
        CDPUserMarkDTO cdpUserMarkDTO = new CDPUserMarkDTO();
        cdpUserMarkDTO.setuKey(String.valueOf(wid));
        cdpUserMarkDTO.setuKeyType("wid");
        cdpUserMarkDTO.setsChannelType(203);
        cdpUserMarkDTO.setsChannelId(privateSphere.getProductInstanceId());
        cdpUserMarkDTO.setBosId(privateSphere.getBosId());
        cdpUserMarkDTO.setUpdateTime(String.valueOf(System.currentTimeMillis()));
        CdpDataJsonInfo cdpDataJsonInfo = new CdpDataJsonInfo();
        cdpDataJsonInfo.setProductInstanceId(privateSphere.getProductInstanceId());
        cdpDataJsonInfo.setWid(wid);
        cdpDataJsonInfo.setCorpId(privateSphere.getCorpId());
        cdpDataJsonInfo.setExternalUserId(customer.getExternalUserid());
        cdpDataJsonInfo.setCustomerStatus(customer.getStatus().getCode());
        //好友标识
        if (Objects.nonNull(friended)) {
            cdpDataJsonInfo.setFlowStatus(friended);
        }
        cdpUserMarkDTO.setDataJson(JSON.parseObject(JSON.toJSONString(cdpDataJsonInfo)));
        cdpUserMarkDTO.setCdpMarkTypeEnum(CDPMarkTypeEnum.CDP_USER_ATTRIBUTE);
        cdpUserMarkDTO.setCdpMarkMessageEventEnum(CdpMarkMessageEventEnum.CUSTOMER_ATTRIBUTE);
        log.info("员工授权范围/坐席变更，CDP打点属性事件：request {}", JSON.toJSON(cdpUserMarkDTO));
        cdpUserAdapterService.markCDPUserMsg(cdpUserMarkDTO);
    }
}
